﻿using FlyingEye.MonitorService;
using Quartz;

namespace FlyingEye.TaskSchedulers
{
    public static class ServiceCollectionExtensions
    {
        public static IServiceCollection AddTaskSchedulers(this IServiceCollection services)
        {
            services.AddQuartz(q =>
            {
                var jobKey = nameof(DevicePartRuntimeMonitorJob);

                q.AddJob<DevicePartRuntimeMonitorJob>(options =>
                {
                    options.WithIdentity(jobKey)
                    .WithDescription("设备部件生命周期更新工作");
                });

                q.AddTrigger(options =>
                {
                    options.ForJob(jobKey)
                    .WithIdentity($"{jobKey}.only.once.trigger")
                    .StartNow()
                    .WithSimpleSchedule(x => x.WithRepeatCount(0)); // 不重复执行
                });

                q.AddTrigger(options =>
                {
                    options.ForJob(jobKey)
                    .WithIdentity($"{jobKey}.trigger")
                    // 每天早上 8 点执行
                    .WithCronSchedule("0 0 8 * * ?", cron =>
                    {
                        // 获取 utc 偏移
                        var offset = TimeZoneInfo.Utc.BaseUtcOffset;
                        // UT+8 使用中国标准时间
                        var china = TimeZoneInfo.CreateCustomTimeZone(Guid.NewGuid().ToString(),
                            offset.Add(TimeSpan.FromHours(8)),
                            "China Standard Time",
                            "China Standard Time");

                        cron.InTimeZone(china);
                    })
                    .WithDescription("每天早上 8 点执行部件运行信息更新工作");
                });
            });

            services.AddQuartzHostedService(q =>
            {
                q.WaitForJobsToComplete = true;
            });

            return services;
        }
    }
}
